package com.ruoyi.framework.datafill;

import com.alibaba.ttl.TtlRunnable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class FillThreadPoolManager {

    private final ThreadPoolTaskExecutor executor;

    public FillThreadPoolManager(){
        this.executor = MdcThreadPoolTaskExecutor.newWithInheritedMdc(10, 100, 30, TimeUnit.SECONDS, 20);
        this.executor.setThreadNamePrefix("fill-thread-"); // 线程名前缀
        this.executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 调用者线程执行
        this.executor.initialize();
    }


    /**
     * 打印填充线程池基本信息
     */
    @ManagedOperation
    public void printPoolExecutorInfo() {
        log.info("填充线程池corePoolSize:{}、maximumPoolSize:{}.", executor.getCorePoolSize(), executor.getMaxPoolSize());
    }

    public void awaitSubmit(List<FillTask> tasks){
        List<? extends Future<?>> futures = tasks.stream().map(TtlRunnable::get).map(executor::submit).toList();
        futures.forEach(future -> {
            try {
                future.get();
            } catch (Exception e) {
                log.error("填充数据异常", e);
            }
        });
    }
}
